var Q = require("q");
var entityCollection = require('../../../Base/server/controllers/EntityCollection');

//开工
exports.syncMOStart = function(req, res) {
	find(req, res).then(insertOrUpdate).catch(function(err) {
		res.json({
			Error: err
		});
	}).done();
};

//核准
exports.syncMOApprove = function(req, res) {
	find(req, res).then(deleteMO).catch(function(err) {
		res.json({
			Error: err
		});
	}).done();
};

//终止
exports.syncMOCancel = function(req, res) {
	find(req, res).then(cancelMO).catch(function(err) {
		res.json({
			Error: err
		});
	}).done();
};

function find(req, res) {
	var deferred = Q.defer();
	var entityItem = entityCollection.getEntity("MO");
	var parameter = req.body; //.Parameter,
	ID = parameter.ID;
	entityItem.find({
		ErpId: ID
	}, null, null, function(err, records) {
		if (!err) {
			var params = {
				req: req,
				res: res,
				records: records
			};
			deferred.resolve(params);
		} else {
			deferred.reject(err);
		}
	});

	return deferred.promise;
};


function insertOrUpdate(result) {
	var deferred = Q.defer();
	var entityMO = entityCollection.getEntity("MO");
	var parameter = result.req.body; //.Parameter;
	var ID = parameter.ID;
	var ItemMaster = parameter.ItemMaster;
	var entityItem = entityCollection.getEntity("ItemMaster");

	var record = {};
	if (result.records.length < 1) {
		record.Code = parameter.DocNo;
		record.LotNumber = "";
		if (parameter.DemandCode != undefined && parameter.DemandCode != null && parameter.DemandCode != "" && parameter.DemandCode.length > 0) {
			record.LotNumber = parameter.DemandCode;
		};
		if (parameter.Seiban != undefined && parameter.Seiban != null && parameter.Seiban != "" && parameter.Seiban.length > 0) {
			record.LotNumber = parameter.Seiban;
		};

		record.Qty = parameter.ProductQty;
		record.StartDateTime = parameter.StartDate;
		record.EndDateTime = parameter.CompleteDate;
		record.Status = 0;
		record.OnlineQty = 0;
		record.Customer = "";
		record.Factory = "";
		record.TotalCompleteQty = 0;
		record.Remark = "";
		record.ErpId = ID;
		entityItem.find({
			ErpId: ItemMaster
		}, null, null, function(err, items) {
			if (err) {
				deferred.reject({
					Error: '输采系统查询料品失败'
				});
			} else {
				if (items.length < 1) {
					deferred.reject({
						Error: '输采系统查询料品失败'
					});
				} else {
					record.ItemMaster = items[0]._id;
					entityMO.insert(record, function(ierr) {
						if (ierr) {
							deferred.reject(ierr);
						} else {
							deferred.resolve(record);
							result.res.json({
								Error: ''
							});
						}
					});
				}
			}
		});

	} else if (result.records.length >= 1) {
		var oldOnlineQty = result.records[0].OnlineQty;
		if (parameter.ProductQty < oldOnlineQty) {
			deferred.reject({
				Error: '生产数量' + parameter.ProductQty + '小于上线数量' + oldOnlineQty
			});
		} else {
			record.Qty = parameter.ProductQty;
			record.StartDateTime = parameter.StartDate;
			record.EndDateTime = parameter.CompleteDate;
			entityMO.updateByValue({
				ErpId: ID
			}, record, function(err, rcd) {
				if (err) {
					deferred.reject(err);
				} else {
					deferred.resolve(rcd);
					result.res.json({
						Error: ''
					});
				}
			});
		}
	};

	return deferred.promise;
};

function deleteMO(result) {
	var deferred = Q.defer();
	var entityMO = entityCollection.getEntity("MO");
	var parameter = result.req.body; //.Parameter;
	var ID = parameter.ID;
	if (result.records.length < 1) {
		deferred.reject({
			Error: '输采系统中未找到对应工单'
		});
	} else {
		if (result.records[0].Status != 0) {
			deferred.reject({
				Error: '工单在输采系统中已上线，无法执行此操作'
			});
		} else {
			entityMO.delete({
				ErpId: ID
			}, function(err) {
				if (err) {
					deferred.reject(err);
				} else {
					deferred.resolve();
					result.res.json({
						Error: ''
					});
				}
			});
		};
	}
	return deferred.promise;
};

function cancelMO(result) {
	var deferred = Q.defer();
	var entityMO = entityCollection.getEntity("MO");
	var parameter = result.req.body; //.Parameter;
	var ID = parameter.ID;
	if (result.records.length < 1) {
		deferred.reject({
			Error: '输采系统中未找到对应工单'
		});
	} else {
		if (result.records[0].Status != 0) {
			deferred.reject({
				Error: '工单在输采系统中已上线，请先执行下线操作'
			});
		} else {
			entityMO.updateByValue({
				ErpId: ID
			}, {
				Status: 3
			}, function(err, rcd) {
				if (err) {
					deferred.reject(err);
				} else {
					deferred.resolve(rcd);
					result.res.json({
						Error: ''
					});
				}
			});
		};
	}
	return deferred.promise;
};